<template>
  <div class="add-download-container">
    <div class="input-section">
      <div class="input-group">
        <input 
          v-model="downloadLink" 
          type="text" 
          placeholder="粘贴下载链接（支持 P2P 链接或 HTTP/HTTPS 直接链接）"
          class="link-input"
          @keyup.enter="parseLink"
        />
        <button @click="parseLink" class="parse-btn">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M9 5H7C5.89543 5 5 5.89543 5 7V19C5 20.1046 5.89543 21 7 21H17C18.1046 21 19 20.1046 19 19V7C19 5.89543 18.1046 5 17 5H15" stroke="currentColor" stroke-width="2"/>
            <path d="M9 5C9 3.89543 9.89543 3 11 3H13C14.1046 3 15 3.89543 15 5V7H9V5Z" stroke="currentColor" stroke-width="2"/>
          </svg>
          解析链接
        </button>
      </div>

      <div v-if="parsedConfig" class="config-panel">
        <div class="config-row">
          <div class="config-item">
            <label>文件名</label>
            <input v-model="parsedConfig.filename" type="text" />
          </div>
          <div class="config-item">
            <label>保存路径</label>
            <div class="path-input">
              <input v-model="savePath" type="text" readonly />
              <button @click="selectSavePath" class="browse-btn">浏览</button>
            </div>
          </div>
        </div>

        <div class="config-row" v-if="parsedConfig.type === 'p2p'">
          <div class="config-item">
            <label>分片总数</label>
            <input v-model.number="parsedConfig.shardCount" type="number" min="1" />
          </div>
          <div class="config-item" v-if="parsedConfig.rsConfig">
            <label>纠删码配置</label>
            <div class="rs-config">
              <span>数据分片: {{ parsedConfig.rsConfig.dataShards }}</span>
              <span>校验分片: {{ parsedConfig.rsConfig.parityShards }}</span>
            </div>
          </div>
        </div>

        <div class="config-row" v-if="parsedConfig.type === 'direct'">
          <div class="config-item">
            <label>下载类型</label>
            <div class="type-badge">
              <span class="badge direct">🔗 直接下载</span>
            </div>
          </div>
          <div class="config-item">
            <label>源地址</label>
            <input :value="parsedConfig.url" type="text" readonly />
          </div>
        </div>

        <div class="peers-section" v-if="parsedConfig.type === 'p2p' && parsedConfig.peers.length > 0">
          <label>对等节点 ({{ parsedConfig.peers.length }})</label>
          <div class="peers-list">
            <div v-for="(peer, index) in parsedConfig.peers" :key="index" class="peer-item">
              <span class="peer-icon">🌐</span>
              <span class="peer-url">{{ peer }}</span>
            </div>
          </div>
        </div>

        <button @click="startDownload" class="download-btn" :disabled="!savePath">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 3V15M12 15L8 11M12 15L16 11" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            <path d="M3 15V19C3 20.1046 3.89543 21 5 21H19C20.1046 21 21 20.1046 21 19V15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
          开始下载
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useDownloadStore } from '../stores/downloadStore';

const emit = defineEmits(['add-download']);
const downloadStore = useDownloadStore();

const downloadLink = ref('');
const parsedConfig = ref(null);
const savePath = ref('');

const parseLink = async () => {
  if (!downloadLink.value.trim()) return;
  
  const link = downloadLink.value.trim();
  
  // 检测链接类型
  if (link.startsWith('http://') || link.startsWith('https://')) {
    // 普通 HTTP 链接
    const filename = link.split('/').pop().split('?')[0] || 'download';
    parsedConfig.value = {
      filename,
      type: 'direct',
      url: link,
      peers: [],
      shardCount: 1,
      rsConfig: null
    };
    // 自动设置默认路径
    applyDefaultPath(filename);
    return;
  }
  
  // P2P 链接
  if (window.electronAPI) {
    const result = await window.electronAPI.parseLink(link);
    if (result.success) {
      parsedConfig.value = { ...result.config, type: 'p2p' };
      // 自动设置默认路径
      applyDefaultPath(result.config.filename);
    } else {
      alert('链接解析失败: ' + result.error);
    }
  } else {
    // 开发环境模拟
    parsedConfig.value = {
      filename: 'example.zip',
      type: 'p2p',
      peers: ['http://peer1.example.com', 'http://peer2.example.com'],
      shardCount: 100,
      rsConfig: { dataShards: 80, parityShards: 20 }
    };
    applyDefaultPath('example.zip');
  }
};

// 应用默认路径
const applyDefaultPath = (filename) => {
  const defaultPath = downloadStore.settings.defaultPath;
  if (defaultPath && filename) {
    // 使用 path.join 的逻辑组合路径
    const separator = defaultPath.includes('\\') ? '\\' : '/';
    savePath.value = defaultPath + separator + filename;
  } else {
    savePath.value = '';
  }
};

const selectSavePath = async () => {
  if (window.electronAPI) {
    const path = await window.electronAPI.selectSavePath(parsedConfig.value.filename);
    if (path) {
      savePath.value = path;
    }
  }
};

const startDownload = () => {
  if (!parsedConfig.value || !savePath.value) return;
  
  emit('add-download', {
    filename: parsedConfig.value.filename,
    type: parsedConfig.value.type,
    url: parsedConfig.value.type === 'direct' ? parsedConfig.value.url : downloadLink.value,
    savePath: savePath.value,
    peers: parsedConfig.value.peers || [],
    shardCount: parsedConfig.value.shardCount,
    rsConfig: parsedConfig.value.rsConfig
  });
  
  // 重置
  downloadLink.value = '';
  parsedConfig.value = null;
  savePath.value = '';
};

// 暴露方法供父组件调用
defineExpose({
  setDownloadLink: (link) => {
    downloadLink.value = link;
    parseLink();
  }
});
</script>

<style scoped>
.add-download-container {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-radius: 1rem;
  padding: 1.5rem;
  margin-bottom: 2rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.input-group {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.link-input {
  flex: 1;
  padding: 0.875rem 1.25rem;
  background: rgba(0, 0, 0, 0.3);
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.5rem;
  color: #e0e0e0;
  font-size: 0.95rem;
  transition: all 0.3s ease;
}

.link-input:focus {
  outline: none;
  border-color: #00d4ff;
  box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.1);
}

.link-input::placeholder {
  color: #707070;
}

.parse-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.875rem 1.5rem;
  background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%);
  border: none;
  border-radius: 0.5rem;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.parse-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 212, 255, 0.4);
}

.parse-btn svg {
  width: 1.25rem;
  height: 1.25rem;
}

.config-panel {
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.config-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-bottom: 1rem;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.config-item label {
  font-size: 0.875rem;
  font-weight: 600;
  color: #a0a0a0;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.config-item input {
  padding: 0.75rem 1rem;
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.5rem;
  color: #e0e0e0;
  font-size: 0.95rem;
}

.path-input {
  display: flex;
  gap: 0.5rem;
}

.path-input input {
  flex: 1;
}

.browse-btn {
  padding: 0.75rem 1rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 0.5rem;
  color: #e0e0e0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.browse-btn:hover {
  background: rgba(255, 255, 255, 0.15);
}

.rs-config {
  display: flex;
  gap: 1rem;
  padding: 0.75rem 1rem;
  background: rgba(123, 47, 247, 0.1);
  border: 1px solid rgba(123, 47, 247, 0.3);
  border-radius: 0.5rem;
  font-size: 0.875rem;
}

.type-badge {
  padding: 0.75rem 1rem;
  background: rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 0.5rem;
}

.badge {
  font-size: 0.875rem;
  font-weight: 600;
}

.badge.direct {
  color: #00d4ff;
}

.peers-section {
  margin-bottom: 1.5rem;
}

.peers-section label {
  display: block;
  margin-bottom: 0.75rem;
  font-size: 0.875rem;
  font-weight: 600;
  color: #a0a0a0;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.peers-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 0.5rem;
  max-height: 150px;
  overflow-y: auto;
  padding: 0.5rem;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 0.5rem;
}

.peer-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 0.375rem;
  font-size: 0.875rem;
}

.peer-icon {
  font-size: 1rem;
}

.peer-url {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #00d4ff;
}

.download-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.75rem;
  width: 100%;
  padding: 1rem;
  background: linear-gradient(135deg, #7b2ff7 0%, #5a1fb8 100%);
  border: none;
  border-radius: 0.5rem;
  color: white;
  font-size: 1rem;
  font-weight: 700;
  cursor: pointer;
  transition: all 0.3s ease;
}

.download-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(123, 47, 247, 0.4);
}

.download-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.download-btn svg {
  width: 1.5rem;
  height: 1.5rem;
}
</style>

